package com.briup.security.service;

import com.briup.security.bean.Account;
import com.briup.security.dao.AccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service("myDetailService")
public class MyDetailService implements UserDetailsService {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountDao.findByUsername(username);
        if (Objects.isNull(account)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        User user =
                new User(account.getUsername(),
                        passwordEncoder.encode(account.getPassword()),
                        AuthorityUtils.createAuthorityList("admin"));
        return user;
    }
}
